import Taro, { Component } from '@tarojs/taro'
// 引入 Form 组件
import { View, Text } from '@tarojs/components'
import { AtInput, AtIcon} from 'taro-ui'
import { connect } from '@tarojs/redux'
import "taro-ui/dist/weapp/components/swipe-action/index.scss"
import './index.styl'
import { queryShopMoney } from '../../api/user'


import {
  asyncCreateShopOrder 
} from '../../api/order'
import {asyncUserMoney} from '../../actions/user'
import {asyncGetUserCoupoon, resetUserCoupon} from '../../actions/coupon'
import {asyncGetUserdVoucher, resetUserVoucher} from '../../actions/voucher'

@connect(({ cart, address, coupon, user, shop, good,voucher }) => ({
  cart, address, coupon, user, shop, good,voucher
}), (dispatch) => ({
 // 加载用户余额
 onAsyncUserMoney () {
  dispatch(asyncUserMoney())
},
// 加载优惠券
onAsyncUserCoupon (shop_only = false) {
  dispatch(asyncGetUserCoupoon(shop_only))
},
// 加载代金券
onAsyncUserVoucher (shop_only = true) {
  dispatch(asyncGetUserdVoucher(shop_only))
},
// 重置
onResetUserCoupon () {
 // dispatch(resetUserCoupon())
},
// 重置代金
onResetUserVoucher () {
  dispatch(resetUserVoucher())
},

}))
class Benefit extends Component {
  constructor () {
    super(...arguments)
    this.state = this.initialState
  }
  config = {
    navigationBarTitleText: '门店优惠买单',
  }
  get initialState() {
    return {
      totalamount: null, //订单总额
      moneyAA:null,  // 使用余额
      totalmoney:null,  // 实际支付
      select_voucher_id:null, //代金券id
      shop_money:0 // 用户可用余额
    };
  }
  // 输入总价
  handleAallmoneyChange (val) {
    this.setState({
      totalamount: val,
      totalmoney:val,
    })
  }
  // 跳转到优惠券列表
  jumpToCoupon () {
    // 总价
    const total = this.state.totalamount * 100
    Taro.navigateTo({url: `/pages/coupon/index?from=settle&amount=${total}`}) // 表示来自结算页
  }
   // 跳转到代金券列表
   jumpToVoucher () {
    // 总价
     const total = this.state.totalamount * 100

    Taro.navigateTo({url: `/pages/voucher/index?from=settle&amount=${total}`}) // 表示来自结算页
  }

  // 获取用户店铺余额
  queryShopMoneyF() {
    console.info('------------------');
    const { token } = this.props.user
    const { shop_id } = this.props.shop
    queryShopMoney(token, shop_id).then(({ data }) => {
     
      console.info(data);
      this.setState({
       shop_money: data
      })
    })
  }

  createOrder (select_coupon,select_voucher) {
    console.info('daijinqun：'+select_voucher);
    // 获取数据
    const {token} = this.props.user
    const {shop_id} = this.props.shop
    const {money} = this.props.user
    let total_moneyA=this.state.totalmoney
    let total_amountA = this.state.totalamount*100
    let user_moneyA = this.state.shop_money // 可用余额
    let user_moneyB // 花掉的余额
    console.info('=====================')
    console.info(this.state.shop_money)
    console.info(total_amountA)
    if(user_moneyA>total_amountA) {
      user_moneyB = user_moneyA-total_amountA
    } else{
      user_moneyB = user_moneyA
    }
    console.info('user_moneyB：'+user_moneyB);

   



    asyncCreateShopOrder({
      token,
        type_id: 3, // 类型id
        shop_id, // 店铺id
      total_money: total_moneyA , // 订单实付金额，以分为单位
      total_amount: total_amountA, // 订单总额
        user_money: user_moneyB, // 余额支付部分
       
        user_coupon_id: select_coupon && select_coupon.id,  //优惠券id,为空表示没有使用优惠券
      user_voucher_id:  this.state.select_voucher_id,  //优惠券id,为空表示没有使用优惠券
        address_id: null, // 收货地址id 为空表示到店自取
        shipping_fee:  0, // 收货地址id 为空表示到店自取,运费
        form_id: null
    }).then(({status,data}) => {
      // 支付金额为0的跳转到订单页
      if (status && total_moneyA==0) {
        Taro.redirectTo({ url: `/pages/order/index?from=settle&tab=0` }) // 表示来自结算页
      }
      if (status) {
        let params ={
          timeStamp:data.timeStamp.toString(),
          nonceStr:data.nonceStr,
          package:data.package,
          signType:data.signType,
          paySign:data.paySign,
        }
        Taro.requestPayment(params).then((res)=>{
          if(res.errMsg=='requestPayment:ok'){
            Taro.redirectTo({url: `/pages/order/index?from=settle&tab=0`}) // 表示来自结算页
          }else{
            throw '支付遇到问题请联系客服!'
          }
        })
        // 列表购买
        // Taro.redirectTo({url: `/pages/order/index?from=settle&tab=0`}) // 表示来自结算页
        // console.log("666666666")

      } else {
        throw '订单创建失败!'
      }
    }).catch(e => {
      console.error(e)
    })
  }
  componentDidShow () {
    // const {token} = this.props.user
    // 重置优惠券
    this.props.onResetUserCoupon()
    // 加载优惠券列表
    this.props.onAsyncUserCoupon(true)
    // 获取用户余额
    this.props.onAsyncUserMoney()

    // 加载用户店铺余额
    this.queryShopMoneyF()
  }
  render () {  
    const { totalamount} = this.state
    const  shop_money = this.state.shop_money

    // 处理优惠券
    const {select_coupon_id, list: coupon_ist} = this.props.coupon
    const canUsedCoupon = coupon_ist.filter(coupon => coupon.coupon.min_amount * 100 <= totalamount * 100)  // 可用券的数量
    const select_coupon = select_coupon_id ? canUsedCoupon.find(coupon => coupon.id = select_coupon_id) : null

      // 处理代金券
      const {select_voucher_id,  data: listVoucher} = this.props.voucher
    const canUsedVoucher = listVoucher.filter(coupon => coupon.value * 100 <= totalamount*100)  // 可用券的数量
      console.info('*****************');
    console.info('totalamount:' + totalamount);
    console.info(listVoucher)
    console.info(canUsedVoucher)
    console.info('select_voucher_id: ' + select_voucher_id);
    console.info('**********************')
    const select_voucher = select_voucher_id ? canUsedVoucher.find(coupon => coupon.id == select_voucher_id) : null
  
    let total
    total = this.state.totalamount 
    let moneyA  =  this.state.shop_money
    console.log(total)
    if (select_coupon && total > 0) {
      total = (total - select_coupon.coupon.value)
      if (total < 0) total = 0
    }
    if (select_voucher && total > 0) {
      console.info('kkakk:'+select_voucher.value);
      total = (total - select_voucher.value)
      console.info('jine:' + total +'select_voucher.value');
      this.state.totalmoney = total;
      this.state.select_voucher_id = select_voucher_id;
      console.info('this.state.totalmoney:' + this.state.totalmoney);
      if (total < 0) total = 0
    }

    if(total>0){
      total = total * 100
      if(total>moneyA){
        total = total - moneyA
        moneyA = 0
      }else{
        moneyA = moneyA-total
        total = 0
      }
      this.state.totalmoney = total;
    }
   
   
    return (
      <View className='benefit'>
     
        {/* 表单 */}
        <View className='benefit-from coupon'>
          <View className='at-row benefit-input'>
            <View className='at-col at-col-6 label'>
              商品总价
            </View>
            <View className='at-col at-col-1 at-col__offset-3 label'>
              ￥
            </View>
            <View className='at-col at-col-2'>
              <AtInput
                name='allmoney' 
                type='text'
                value={totalamount}
                placeholder='0.00'
                onChange={this.handleAallmoneyChange.bind(this)}
              />
            </View>
          </View>
          {/*优惠券*/}
          {select_coupon && <View className='address-select'  onClick={this.jumpToCoupon.bind(this)}>
            <Text className='label'>优惠券</Text>
            <Text className='placeholder'>
              {select_coupon && <Text>-{parseFloat(select_coupon.coupon.value).toFixed(2)}</Text>}
              {!select_coupon && <Text>{canUsedCoupon.length > 0  ? `${canUsedCoupon.length} 优惠券可用` : '无可用优惠券'}</Text>}
            </Text>
            <AtIcon className='arrow' value='chevron-right' size='16' color='#B2B2B2' />
          </View>}
           {/*代金券 */}
           { <View onClick={this.jumpToVoucher.bind(this)} className='item'>
            <View className='left'>
              <Text className='small'>代金券</Text>
            </View>
            <View className='right coupon-right'>
              {/* {!select_voucher && <Text> 无可用代金券</Text>}
              <AtIcon value='chevron-right' size='12' color='#B2B2B2' /> */}
              {select_voucher && <Text>-{parseFloat(select_voucher.value).toFixed(2)}</Text>}
              {!select_voucher && <Text>{canUsedVoucher.length > 0  ? `${canUsedVoucher.length} 代金券可用` : '无可用代金券'}</Text>}
              <AtIcon value='chevron-right' size='12' color='#B2B2B2' />
            </View>
          </View>}
          {/* <View className='address-select'>
            <Text className='label'>优惠券</Text>
            <Text className='placeholder'>无可用优惠券</Text>
            <AtIcon className='arrow' value='chevron-right' size='16' color='#B2B2B2' />
          </View> */}
          <View className='at-row benefit-balance'>
            <View className='at-col at-col-6 label'>
              余额
            </View>
            <View className='at-col at-col-1 at-col__offset-3 label'>
              ￥
            </View>
            <View className='at-col at-col-2 label'>
             {shop_money !== null && <Text className='surplus-money'>{parseFloat( shop_money/100 ).toFixed(2)}</Text>}
            </View>
          </View>
          <View className='benefit-payment'>
            <View className='payment-title'>商品应付</View>
            <View className='payment-num'>{parseFloat(total/100 ).toFixed(2)}</View>
          </View>
          <View className='benefit-explain'>
            <View className='explain-title'>门店优惠买单说明</View>
            <View className='explain-content'>
              <View className='content-title'>1. 输入金额，使用代金券和余额后提交订单;</View>
              <View className='content-title'>2. 支付后进入我的订单出示收货码，门店扫码确认;</View>
            </View>
          </View>
        </View>
        <View className='footer-btn'>
          <View className='checkout-btn'  onClick={this.createOrder.bind(this)}>提交订单</View>
          </View>
        {/*底部*/}
        {/* <View className='footer'>
          <View className='checkout'  onClick={this.createOrder.bind(this)}>提交订单</View>
        </View> */}

    
      </View>
     
    )
  }
  }
  
  export default Benefit
  